package com.example.mypra1.fragments;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.mypra1.DianzanActivity;
import com.example.mypra1.GuanzhuActivity;
import com.example.mypra1.LoginActivity;
import com.example.mypra1.R;
import com.example.mypra1.UserInfoActivity;
import com.example.mypra1.adapter.MyListAdapter;
import com.example.mypra1.adapter.entity.Comment;
import com.szysky.customize.siv.SImageView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 我的模块
 */
public class MainFragment4 extends Fragment {
    private Context mContext;
    private View rootView;
    private ViewGroup mContentView;
    private TextView logout,guanzhu_tv,dianzan_tv;
    private String profile;
    private String username;
    private SImageView profile_iv;
    private TextView username_tv;
    private RelativeLayout userInfo;
    private LinearLayout guanzhu_btn,dianzan_btn;
    private int id,guanzhu,dianzan;
    private List<Comment>comments1,comments2;
    private Handler handler1=new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {//操作UI,渲染发布条数
            Map<String,Object>map = (Map<String, Object>) msg.obj;
            comments1 = (List<Comment>) map.get("comments");
            guanzhu_tv = rootView.findViewById(R.id.guanzhu);
            guanzhu = comments1.size();
            guanzhu_tv.setText(String.valueOf(guanzhu));
        }
    };
    private Handler handler2=new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {//操作UI,渲染点赞条数
            Map<String,Object>map = (Map<String, Object>) msg.obj;
            comments2 = (List<Comment>) map.get("comments");
            dianzan_tv = rootView.findViewById(R.id.dianzan);
            dianzan = comments2.size();
            dianzan_tv.setText(String.valueOf(dianzan));
        }
    };
    public static MainFragment4 newInstance() {
        Bundle args = new Bundle();
        MainFragment4 fragment = new MainFragment4();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.main_fragment4, container, false);
        }
        Activity activity = getActivity();
        //从SharedPreference中获取用户当前信息
        SharedPreferences pref = activity.getSharedPreferences("data",Context.MODE_PRIVATE);
        profile = pref.getString("profile","");
        username = pref.getString("username","");
        id = pref.getInt("id",1);
        username_tv = rootView.findViewById(R.id.username);
        profile_iv = rootView.findViewById(R.id.profile);
        profile_iv.setImageUrls(profile);
        //点击头像，实现刷新(用户修改个人信息后重新获取昵称等数据)
        profile_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences pref = activity.getSharedPreferences("data",Context.MODE_PRIVATE);
                   username = pref.getString("username","");
                   username_tv.setText(username);
            }
        });
        username_tv.setText(username);
        guanzhu_tv = rootView.findViewById(R.id.guanzhu);
        dianzan_tv = rootView.findViewById(R.id.dianzan);
        userInfo = rootView.findViewById(R.id.userInfo);
        logout = rootView.findViewById(R.id.logout);
        guanzhu_btn = rootView.findViewById(R.id.guanzhu_btn);
        dianzan_btn = rootView.findViewById(R.id.dianzan_btn);
        guanzhu_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext.getApplicationContext(), GuanzhuActivity.class);
                startActivity(intent);
            }
        });
        dianzan_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext.getApplicationContext(), DianzanActivity.class);
                startActivity(intent);
            }
        });
        //退出登录
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences pref = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = pref.edit();
                editor.clear();
                editor.commit();//清除存储在SharedPreference中的用户信息
                Intent intent = new Intent(mContext.getApplicationContext(),LoginActivity.class);
                startActivity(intent);
            }
        });
        userInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext.getApplicationContext(), UserInfoActivity.class);
                startActivity(intent);
            }
        });
        //发送网络请求，获取当前用户的发布和点赞
        getData1();
        getData2();
        return rootView;
    }
    //发送get请求获取当前用户发布的内容
    private void getData1(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://8.142.19.67:3000/myComments?pubid="+id)
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException,RuntimeException {
                            Log.d("resp",response.toString());
                            if (response.isSuccessful()) {
                                String res = response.body().string();
                                Log.d("res",res);
                                try {
                                    JSONObject jsonObject = new JSONObject(res);
                                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                                    Log.d("array",jsonArray.toString());
                                    Map<String,Object> map = new HashMap<>();
                                    List<Comment> comments1 = new ArrayList<>();
                                    for(int i=0;i<jsonArray.length();i++){
                                        JSONObject object = jsonArray.getJSONObject(i);
                                        comments1.add(new Comment(object.getInt("id"),object.getInt("pubid"),
                                               username,profile,object.getString("content"),
                                                object.getString("imgs"),object.getString("pubtime"),object.getInt("favor"),
                                                object.getInt("repcount")));
                                    }
                                    map.put("comments",comments1);
                                    Message message = new Message();
                                    message.obj = map;
                                    handler1.sendMessage(message);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }else{
                                Log.d("resp",response.toString());
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    //发送get请求，获取当前用户所点赞过的评论
    private void getData2(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://8.142.19.67:3000/favorComments")
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException,RuntimeException {
                            Log.d("resp",response.toString());
                            if (response.isSuccessful()) {
                                String res = response.body().string();
                                Log.d("res",res);
                                try {
                                    JSONObject jsonObject = new JSONObject(res);
                                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                                    Map<String,Object> map = new HashMap<>();
                                    List<Comment> comments1 = new ArrayList<>();
                                    for(int i=0;i<jsonArray.length();i++){
                                        JSONObject object = jsonArray.getJSONObject(i);
                                        comments1.add(new Comment(object.getInt("id"),object.getInt("pubid"),
                                                username,profile,object.getString("content"),
                                                object.getString("imgs"),object.getString("pubtime"),object.getInt("favor"),
                                                object.getInt("repcount")));
                                    }
                                    map.put("comments",comments1);
                                    Message message = new Message();
                                    message.obj = map;
                                    handler2.sendMessage(message);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }else{
                                Log.d("resp",response.toString());
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
